<template>
  <div class="bg-white rounded-lg p-3 w-full">
    <!-- 顶部搜索和操作区 -->
    <div class="flex justify-between items-center mb-4">
      <div class="flex gap-2">
        <el-form :inline="true" :model="searchForm" class="flex items-center gap-2">
          <el-form-item label="姓名" class="mb-0">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入医生姓名"
              class="w-60"
              clearable
            />
          </el-form-item>
          <el-form-item label="科室" class="mb-0">
            <el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable class="w-60">
              <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="mb-0">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAddDoctor">新增医生</el-button>
            <el-button type="warning" @click="showDepartmentDialog = true">科室设置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 医生列表 -->
    <el-table :data="tableData" stripe border >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="phone" label="联系电话" min-width="120" />
      <el-table-column prop="departmentName" label="科室" min-width="120" />
      <el-table-column prop="title" label="职称" min-width="120" />
      <el-table-column prop="goodAt" label="擅长" min-width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEditDoctor(row)">
            编辑
          </el-button>
          <el-button type="warning" link @click="handleDeleteDoctor(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end">
      <Pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 医生新增/编辑对话框 -->
    <Drawer
      v-model="showDoctorDialog"
      :title="doctorForm.id ? '编辑医生' : '新增医生'"
      size="500px"
      @confirm = "handleConfirmDoctor"
    >
      <el-form
        ref="doctorFormRef"
        :model="doctorForm"
        :rules="doctorRules"
        label-width="80px"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="doctorForm.name" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="doctorForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="科室：" prop="departmentId">
          <el-select v-model="doctorForm.departmentId" placeholder="请选择科室" class="w-full">
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称：" prop="title">
          <el-select v-model="doctorForm.title" placeholder="请选择职称" class="w-full">
            <el-option label="主任医师" value="主任医师" />
            <el-option label="副主任医师" value="副主任医师" />
            <el-option label="主治医师" value="主治医师" />
            <el-option label="住院医师" value="住院医师" />
          </el-select>
        </el-form-item>
        <el-form-item label="擅长：" prop="goodAt">
          <el-input v-model="doctorForm.goodAt" type="textarea" />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 科室设置对话框 -->
    <Drawer
      v-model="showDepartmentDialog"
      title="科室设置"
      size="600px"
      @confirm = "handleConfirmDepartment"
    >
      <div class="flex justify-between mb-4">
        <el-input
          v-model="newDepartmentName"
          placeholder="请输入科室名称"
          class="w-2/3"
        >
          <template #append>
            <el-button type="primary" @click="handleAddDepartment">
              添加
            </el-button>
          </template>
        </el-input>
      </div>

      <el-table :data="departmentOptions" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="科室名称" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditDepartment(row)">
              编辑
            </el-button>
            <el-button type="warning" link @click="handleDeleteDepartment(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </Drawer>

    <!-- 编辑科室对话框 -->
    <Drawer
      v-model="showEditDepartmentDialog"
      title="编辑科室"
      size="400px"
      @confirm = "handleConfirmDepartment"
    >
      <el-form
        ref="departmentFormRef"
        :model="editingDepartment"
        :rules="departmentRules"
        label-width="80px"
      >
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="editingDepartment.name" placeholder="请输入科室名称" />
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Drawer from '@/components/common/Drawer.vue'
import Pagination from '@/components/common/Pagination.vue'

// 搜索表单
const searchForm = ref({
  name: '',
  departmentId: ''
})

// 表格数据和加载状态
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showConfirmBtn = ref(false)
// 科室选项
const departmentOptions = ref([
  { id: 1, name: '内科' },
  { id: 2, name: '外科' },
  { id: 3, name: '儿科' },
  { id: 4, name: '妇产科' }
])

// 医生表单
const showDoctorDialog = ref(false)
const doctorFormRef = ref()
const doctorForm = ref({
  id: '',
  name: '',
  phone: '',
  departmentId: '',
  title: '',
  goodAt: ''
})

// 医生表单验证规则
const doctorRules = {
  name: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }]
}

// 科室设置
const showDepartmentDialog = ref(false)
const newDepartmentName = ref('')

// 科室编辑
const showEditDepartmentDialog = ref(false)
const departmentFormRef = ref()
const editingDepartment = ref({
  id: '',
  name: ''
})

// 科室表单验证规则
const departmentRules = {
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}
// 科室确认
const handleConfirmDepartment = () => {
  ElMessage.success('科室已确认')
  showDepartmentDialog.value = false
}


// 初始化数据
onMounted(() => {
  loadDoctorList()
})

// 加载医生列表
const loadDoctorList = async () => {
  loading.value = true
  try {
    // 这里调用后端接口获取数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    tableData.value = [
      {
        id: 1,
        name: '张医生',
        phone: '13800138000',
        departmentId: 1,
        departmentName: '内科',
        title: '主任医师',
        goodAt: '擅长治疗各种内科疾病'
      }
    ]
    total.value = 1
  } catch (error) {
    console.error(error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadDoctorList()
}

// 新增医生
const handleAddDoctor = () => {
  doctorForm.value = {
    id: '',
    name: '',
    phone: '',
    departmentId: '',
    title: '',
    goodAt: ''
  }
  showDoctorDialog.value = true
}

// 编辑医生
const handleEditDoctor = (row) => {
  doctorForm.value = { ...row }
  showDoctorDialog.value = true
}
// 新增医生保存
const handleConfirmDoctor = async () => {
  if (!doctorFormRef.value) return
  await doctorFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里调用后端接口保存数据
        await new Promise(resolve => setTimeout(resolve, 500))
        ElMessage.success('保存成功')
        showDoctorDialog.value = false
        loadDoctorList()
      } catch (error) {
        console.error(error)
        ElMessage.error('保存失败')
      }
    }
  })
}
// 删除医生
const handleDeleteDoctor = (row) => {
  ElMessageBox.confirm('确定要删除该医生吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      // 这里调用后端接口删除数据
      await new Promise(resolve => setTimeout(resolve, 500))
      ElMessage.success('删除成功')
      loadDoctorList()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  })
}

// 添加科室
const handleAddDepartment = async () => {
  if (!newDepartmentName.value) {
    ElMessage.warning('请输入科室名称')
    return
  }
  try {
    // 这里调用后端接口添加科室
    await new Promise(resolve => setTimeout(resolve, 500))
    departmentOptions.value.push({
      id: Date.now(),
      name: newDepartmentName.value
    })
    newDepartmentName.value = ''
    ElMessage.success('添加成功')
  } catch (error) {
    console.error(error)
    ElMessage.error('添加失败')
  }
}

// 删除科室
const handleDeleteDepartment = (row) => {
  ElMessageBox.confirm('确定要删除该科室吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      // 这里调用后端接口删除科室
      await new Promise(resolve => setTimeout(resolve, 500))
      departmentOptions.value = departmentOptions.value.filter(item => item.id !== row.id)
      ElMessage.success('删除成功')
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  })
}

// 编辑科室
const handleEditDepartment = (row) => {
  editingDepartment.value = { ...row }
  showEditDepartmentDialog.value = true
}

// 保存科室信息
const handleSaveDepartment = async () => {
  if (!departmentFormRef.value) return
  await departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里调用后端接口保存数据
        await new Promise(resolve => setTimeout(resolve, 500))
        // 更新本地数据
        const index = departmentOptions.value.findIndex(item => item.id === editingDepartment.value.id)
        if (index !== -1) {
          departmentOptions.value[index] = { ...editingDepartment.value }
        }
        ElMessage.success('保存成功')
        showEditDepartmentDialog.value = false
      } catch (error) {
        console.error(error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadDoctorList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadDoctorList()
}
</script>

